<template>
  <view>
    <nav-bar :page-title="lang.pageTitle"/>
    <view :class="['padding-30 text-color text-28', locale]">
      <!-- header -->
      <view class="center margin-bottom-60">
        <text class="text-40">{{ lang.title }}</text>
      </view>

      <!-- selected file section -->
      <view v-if="!selectedFile" class="center gap-40 upload-box" @click="selectPDF">
        <image src="/static/upload/upload.svg" class="upload-icon"/>
        <view class="upload-text">{{ toolBoxLang.selectFile }}</view>
      </view>

      <view v-else class="card flex-between selected-file">
        <view class="flex-center gap-20" style="width: 70%;">
          <view :class="['padding-30 radio-20 center type pdf']">
            <image src="/static/ext/pdf.svg" class="file-icon"/>
          </view>
          <view class="text-to text-32">{{ selectedFile.name }}</view>
        </view>
        <view class="column-center gap-20">
          <button class="btn preview" @click="previewFile(selectedFile)">{{ toolBoxLang.preview }}</button>
          <button class="btn delete" @click="removeFile">{{ toolBoxLang.delete }}</button>
        </view>
      </view>

      <!-- selected file section -->
      <view class="card margin-top flex-between" v-if="selectedFile">
        <view class="column">
          <view class="text-32">{{ lang.splitCount }}</view>
          <view>{{ lang.splitCountLabel }}</view>
        </view>
        <u-number-box v-model="partsCount" @change="handleCustomNum" :min="2" :max="10" integer/>
      </view>

      <!-- result -->
      <view v-if="results" class="result-card">
        <view class="center result-header">
          <text class="text-32 color-white">{{ toolBoxLang.splitComplete }}</text>
        </view>

        <view class="result-content">
          <view v-for="(result, index) in results" :key="index">
            <view class="flex-between result-item">
              <view class="text-32 color-dark-grey">{{ myReplace(lang.part, '{part}', index + 1) }}</view>
              <view class="result-item-value text-color">{{ result.page_count }} {{ otherLang.page }}</view>
            </view>

            <view class="flex-between result-item">
              <view class="text-32 color-dark-grey">{{ toolBoxLang.fileName }}</view>
              <view style="width: 70%">
                <view class="text-32 text-to" style="direction: initial">{{ getFileName(result.url) }}</view>
              </view>
            </view>

            <view class="flex-between gap-20" style="justify-content: space-around">
<!--              <view class="color-white radio-30 center file share" @click="shareFile(result)">-->
<!--                {{ toolBoxLang.share }}-->
<!--              </view>-->
              <view class="color-white radio-30 center file preview" @click="previewFile(result)">
                {{ toolBoxLang.preview }}
              </view>
              <view class="color-white radio-30 center file download" @click="handleDownload(result.url)">
                {{ toolBoxLang.download }}
              </view>
              <view class="color-white radio-30 center file print" @click="printFile(result)">
                {{ toolBoxLang.print }}
              </view>
            </view>

            <view v-if="index !== results.length - 1" class="margin-tb-20">
              <view class="line"/>
            </view>
          </view>
        </view>
      </view>

      <!-- footer -->
      <view class="padding-30 footer">
        <button class="submit-btn" :disabled="!(selectedFile && partsCount >= 2)" @click="handleAction">
          {{ isConverted ? toolBoxLang.selectNewFile : toolBoxLang.startSplit }}
        </button>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import NavBar from "@/components/nav-bar/nav-bar.vue";
import tips from "@/utils/tips";
import RInput from "@/components/RInput/RInput.vue";
import {autoSplitPdfUrl} from "@/services/office";
import {getFileName, myReplace} from "@/utils/utils";

interface FileObject {
  url?: string;
  path?: string;
  name?: string;
}

export default {
  components: {RInput, NavBar},

  data() {
    return {
      selectedFile: null,
      partsCount: 2,
      results: null,
      isConverted: false,
    }
  },

  computed: {
    toolBoxLang() {
      return this.$t('toolBox')
    },
    lang() {
      return this.$t('toolBox.autoSplitPdf')
    }
  },

  methods: {
    myReplace,
    getFileName,
    selectPDF() {
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['.pdf'],
        success: (res) => {
          const {path, name} = res.tempFiles[0]
          console.log({path, name})
          this.selectedFile = {path, name}
        },
      })
    },

    removeFile() {
      this.selectedFile = null
      this.results = null
      this.partsCount = 2
    },

    // preview file
    previewFile(file: FileObject) {
      if (file.url) {
        uni.downloadFile({
          url: file.url,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.openDocument({
                filePath: res.tempFilePath,
                fileType: 'pdf',
                success: () => {
                  console.log(this.toolBoxLang.openSuccess);
                },
              });
            }
          },
        });
      } else {
        uni.openDocument({
          filePath: file.path,
          fileType: 'pdf',
          success: () => {
            console.log(this.lang.openSuccess);
          },
          fail: () => {
            tips.toast(this.lang.openFailed);
          }
        });
      }
    },

    // selected file split parts
    handleCustomNum(e) {
      const {value} = e
      if (value && value >= 2) {
        this.partsCount = value
      }
    },

    // submit file
    handleSubmit() {
      uni.showLoading()
      uni.uploadFile({
        url: autoSplitPdfUrl,
        filePath: this.selectedFile.path,
        name: 'file',
        formData: {parts_count: this.partsCount},
        success: (res) => {
          console.log("res -=-=", res)
          if (res.statusCode == 200) {
            const {data} = JSON.parse(res.data)
            this.isConverted = true
            console.log("data -=-=", data)
            this.results = data
            tips.toast(this.toolBoxLang.splitSuccess)
          } else {
            tips.toast(this.toolBoxLang.splitFailed)
          }
        },
        fail: () => {
          tips.toast(this.toolBoxLang.splitFailed)
        }, complete: () => {
          uni.hideLoading()
        }
      })
    },

    handleAction() {
      if (this.isConverted) {
        this.removeFile()
        this.isConverted = false
      } else {
        this.handleSubmit()
      }
    },

    // share file
    shareFile(file: FileObject) {
      const {url} = file;
      if (!url) {
        tips.toast(this.lang.emptyUrl)
        return;
      }

      console.log('url', url)

      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            console.log("res.tempFilePath =-=", res.tempFilePath)
            uni.shareFileMessage({
              filePath: res.tempFilePath,
              fileName: getFileName(url),
              success: () => {
                console.log('ئىچىش مۇۋاپىقىيەتلىك بولدى');
              }
            });
          }
        }
      });
    },

    // download file
    handleDownload(url: string) {
      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: (resData) => {
                uni.openDocument({
                  filePath: resData.savedFilePath,
                  fileType: 'pdf',
                  showMenu: true,
                  success: () => {
                    console.log('ئىچىش مۇۋاپىقىيەتلىك بولدى');
                  }
                });
              },
              fail: error => {
                console.log('error: ', error)
              }
            })
          }
        }
      });
    },

    // print file
    printFile({url, page_count}) {
      const {selectedFile: {name}} = this;
      if (!url) {
        tips.toast(this.lang.emptyUrl)
        return;
      }
      uni.navigateTo({
        url: `/pages/file/print_file?pages=${page_count}&file=${encodeURIComponent(JSON.stringify({url, name}))}`
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.upload-box {
  border: 2px dashed $uni-border-color;
  padding: 60rpx;

  &:active {
    background: $uni-bg-color-hover;
  }

  .upload-icon {
    width: 80rpx;
    height: 80rpx;
  }

  .upload-text {
    font-size: 32rpx;
    color: $uni-text-dark-grey;
  }
}

.selected-file {
  .file-icon {
    width: 60rpx;
    height: 60rpx;
  }

  .btn {
    font-size: 24rpx;
    color: #fff;
    width: 128rpx;
    border-radius: 12rpx;
    padding: 0;
    margin: 0;

    &.preview {
      background: #007AFF;
    }

    &.delete {
      background: #ff3b30;
    }
  }
}

/** start split btn style */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(to right, #34c759, #30d158);
    color: #fff;
    font-size: 32rpx;
    border-radius: 46rpx;

    &[disabled] {
      background: linear-gradient(to right, #ccc, #ddd);
    }
  }
}

.result-card {
  margin-top: 30rpx;
  border-radius: 20rpx;
  background: #ffffff;
  overflow: hidden;
  margin-bottom: 200rpx;

  .result-header {
    background: $uni-color-success;
    padding: 20rpx;
  }

  .result-content {
    padding: 30rpx;

    .result-item {
      margin-bottom: 20rpx;

      .result-item-value {
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .file {
      width: 140rpx;
      line-height: 34rpx;
      padding: 14rpx 20rpx;
      transition: opacity 0.3s;

      &:active {
        opacity: 0.8;
      }

      &.share {
        background: $uni-color-info;
      }

      &.preview {
        background: $uni-color-warning;
      }

      &.download {
        background: $uni-color-success;
      }

      &.print {
        background: $uni-color-primary;
      }
    }
  }
}
</style>